package com.sheng.leetcode.year2022.swordfingeroffer.day15;

import org.junit.Test;

/**
 * @authers liusheng
 * @date 2022/9/13
 *<p>
 * 剑指 Offer 54. 二叉搜索树的第k大节点<p>
 * <p>
 * 给定一棵二叉搜索树，请找出其中第 k 大的节点的值。<p>
 *<p>
 * 示例 1:<p>
 * 输入: root = [3,1,4,null,2], k = 1<p>
 *    3<p>
 *   / \<p>
 *  1   4<p>
 *   \<p>
 *    2<p>
 * 输出: 4<p>
 * <p>
 * 示例 2:<p>
 * 输入: root = [5,3,6,2,4,null,null,1], k = 3<p>
 *        5<p>
 *       / \<p>
 *      3   6<p>
 *     / \<p>
 *    2   4<p>
 *   /<p>
 *  1<p>
 * 输出: 4<p>
 *<p>
 * 限制：<p>
 *<p>
 * 1 ≤ k ≤ 二叉搜索树元素个数<p>
 *<p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/er-cha-sou-suo-shu-de-di-kda-jie-dian-lcof">...</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class Sword0054 {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(1);
        TreeNode left1 = new TreeNode(2);
        left.right = left1;
        TreeNode right = new TreeNode(4);
        root.left = left;
        root.right = right;
        int k = 1;
        System.out.println(new Solution54().kthLargest(root, k));
    }
}
class Solution54 {
    int res, n;
    public int kthLargest(TreeNode root, int k) {
        n = k;
        dfs(root);
        return res;
    }
    public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.right);
        if (n == 0) {
            return;
        }
        if (--n == 0) {
            res = root.val;
        }
        dfs(root.left);
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
